import React, { useEffect, useState } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Progress,
  Modal,
  Form,
  InputNumber,
  message,
  Row,
  Col,
  Statistic,
  Alert,
  Badge,
  Typography,
  Tooltip,
} from 'antd';
import {
  WarningOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
  SearchOutlined,
  ExportOutlined,
  ReloadOutlined,
  BellOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableRowSelection } from 'antd/es/table';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { Product } from '../../types';

const { Title, Text } = Typography;
const { Search } = Input;
const { Option } = Select;

interface StockAlert {
  id: string;
  productId: string;
  productName: string;
  currentStock: number;
  minStock: number;
  alertType: 'low_stock' | 'out_of_stock';
  createdAt: string;
}

interface StockAdjustment {
  productId: string;
  adjustmentType: 'increase' | 'decrease' | 'set';
  quantity: number;
  reason: string;
}

const StockManagement: React.FC = () => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  
  const [products, setProducts] = useState<Product[]>([]);
  const [stockAlerts, setStockAlerts] = useState<StockAlert[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [adjustModalVisible, setAdjustModalVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '商品管理' },
      { title: '库存管理' },
    ]));
  }, [dispatch]);

  useEffect(() => {
    loadStockData();
    loadStockAlerts();
  }, []);

  // 加载库存数据
  const loadStockData = async () => {
    try {
      setLoading(true);
      // 模拟库存数据
      const mockProducts: Product[] = [
        {
          id: '1',
          name: 'iPhone 15 Pro Max',
          category: '电子产品',
          price: 9999,
          stock: 5, // 库存不足
          salesCount: 1250,
          status: 'active',
          shopName: 'Apple官方旗舰店',
          images: ['https://via.placeholder.com/60x60'],
          description: '',
          createdAt: '2024-01-15T08:00:00Z',
          updatedAt: '2024-01-20T10:30:00Z',
        },
        {
          id: '2',
          name: 'MacBook Pro 16',
          category: '电子产品',
          price: 19999,
          stock: 0, // 缺货
          salesCount: 500,
          status: 'out_of_stock',
          shopName: 'Apple官方旗舰店',
          images: ['https://via.placeholder.com/60x60'],
          description: '',
          createdAt: '2024-01-15T08:00:00Z',
          updatedAt: '2024-01-20T10:30:00Z',
        },
        {
          id: '3',
          name: 'AirPods Pro',
          category: '电子产品',
          price: 1999,
          stock: 150, // 库存充足
          salesCount: 800,
          status: 'active',
          shopName: 'Apple官方旗舰店',
          images: ['https://via.placeholder.com/60x60'],
          description: '',
          createdAt: '2024-01-15T08:00:00Z',
          updatedAt: '2024-01-20T10:30:00Z',
        },
      ];
      
      setProducts(mockProducts);
    } catch (error) {
      message.error('加载库存数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载库存预警
  const loadStockAlerts = async () => {
    try {
      const mockAlerts: StockAlert[] = [
        {
          id: '1',
          productId: '1',
          productName: 'iPhone 15 Pro Max',
          currentStock: 5,
          minStock: 10,
          alertType: 'low_stock',
          createdAt: '2024-01-20T10:00:00Z',
        },
        {
          id: '2',
          productId: '2',
          productName: 'MacBook Pro 16',
          currentStock: 0,
          minStock: 5,
          alertType: 'out_of_stock',
          createdAt: '2024-01-20T09:00:00Z',
        },
      ];
      
      setStockAlerts(mockAlerts);
    } catch (error) {
      message.error('加载预警数据失败');
    }
  };

  // 获取库存状态
  const getStockStatus = (stock: number) => {
    if (stock === 0) {
      return { status: 'error' as const, text: '缺货', color: '#ff4d4f' };
    } else if (stock < 10) {
      return { status: 'warning' as const, text: '库存不足', color: '#faad14' };
    } else if (stock < 50) {
      return { status: 'processing' as const, text: '库存正常', color: '#1890ff' };
    } else {
      return { status: 'success' as const, text: '库存充足', color: '#52c41a' };
    }
  };

  // 批量调整库存
  const handleBatchAdjust = async (values: StockAdjustment) => {
    try {
      // 模拟API调用
      message.success('库存调整成功');
      setAdjustModalVisible(false);
      setSelectedRowKeys([]);
      loadStockData();
    } catch (error) {
      message.error('库存调整失败');
    }
  };

  // 行选择
  const rowSelection: TableRowSelection<Product> = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  // 表格列定义
  const columns: ColumnsType<Product> = [
    {
      title: '商品信息',
      key: 'product',
      width: 300,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <img
            src={record.images[0]}
            alt={record.name}
            style={{ width: 50, height: 50, borderRadius: 4, marginRight: 12 }}
          />
          <div>
            <div style={{ fontWeight: 500 }}>{record.name}</div>
            <div style={{ fontSize: 12, color: '#666' }}>
              分类: {record.category}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: '当前库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 120,
      sorter: (a, b) => a.stock - b.stock,
      render: (stock) => {
        const status = getStockStatus(stock);
        return (
          <div>
            <Badge status={status.status} text={`${stock} 件`} />
            <div style={{ fontSize: 12, color: status.color }}>
              {status.text}
            </div>
          </div>
        );
      },
    },
    {
      title: '库存状态',
      key: 'stockStatus',
      width: 150,
      render: (_, record) => {
        const status = getStockStatus(record.stock);
        const percentage = Math.min((record.stock / 100) * 100, 100);
        return (
          <Progress
            percent={percentage}
            size="small"
            status={status.status}
            format={() => status.text}
          />
        );
      },
    },
    {
      title: '销量',
      dataIndex: 'salesCount',
      key: 'salesCount',
      width: 80,
      sorter: (a, b) => (a.salesCount || 0) - (b.salesCount || 0),
      render: (count) => count || 0,
    },
    {
      title: '店铺',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_, record) => (
        <Space>
          <Tooltip title="调整库存">
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => {
                setSelectedRowKeys([record.id]);
                setAdjustModalVisible(true);
              }}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  // 过滤数据
  const filteredProducts = products.filter(product => {
    const matchKeyword = !searchKeyword || 
      product.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
      product.category.toLowerCase().includes(searchKeyword.toLowerCase());
    
    const matchStatus = !statusFilter || 
      (statusFilter === 'out_of_stock' && product.stock === 0) ||
      (statusFilter === 'low_stock' && product.stock > 0 && product.stock < 10) ||
      (statusFilter === 'normal' && product.stock >= 10);
    
    return matchKeyword && matchStatus;
  });

  return (
    <div style={{ padding: '24px' }}>
      {/* 库存预警 */}
      {stockAlerts.length > 0 && (
        <Alert
          message="库存预警"
          description={
            <div>
              {stockAlerts.map(alert => (
                <div key={alert.id} style={{ marginBottom: 4 }}>
                  <Text strong>{alert.productName}</Text>
                  {alert.alertType === 'out_of_stock' ? (
                    <Text type="danger"> 已缺货</Text>
                  ) : (
                    <Text type="warning"> 库存不足 ({alert.currentStock} 件)</Text>
                  )}
                </div>
              ))}
            </div>
          }
          type="warning"
          showIcon
          icon={<BellOutlined />}
          style={{ marginBottom: '24px' }}
          closable
        />
      )}

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="总商品数"
              value={products.length}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="缺货商品"
              value={products.filter(p => p.stock === 0).length}
              valueStyle={{ color: '#ff4d4f' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="库存不足"
              value={products.filter(p => p.stock > 0 && p.stock < 10).length}
              valueStyle={{ color: '#faad14' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="库存充足"
              value={products.filter(p => p.stock >= 50).length}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作栏 */}
      <Card style={{ marginBottom: '16px' }}>
        <Row gutter={16} align="middle">
          <Col flex="auto">
            <Space>
              <Search
                placeholder="搜索商品名称或分类"
                style={{ width: 300 }}
                onSearch={setSearchKeyword}
                enterButton={<SearchOutlined />}
              />
              <Select
                placeholder="库存状态"
                style={{ width: 120 }}
                allowClear
                onChange={setStatusFilter}
              >
                <Option value="out_of_stock">缺货</Option>
                <Option value="low_stock">库存不足</Option>
                <Option value="normal">库存正常</Option>
              </Select>
            </Space>
          </Col>
          <Col>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={loadStockData}>
                刷新
              </Button>
              <Button icon={<ExportOutlined />}>
                导出
              </Button>
              {selectedRowKeys.length > 0 && (
                <Button
                  type="primary"
                  icon={<EditOutlined />}
                  onClick={() => setAdjustModalVisible(true)}
                >
                  批量调整 ({selectedRowKeys.length})
                </Button>
              )}
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 库存表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={filteredProducts}
          rowKey="id"
          rowSelection={rowSelection}
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 库存调整模态框 */}
      <Modal
        title="库存调整"
        open={adjustModalVisible}
        onCancel={() => setAdjustModalVisible(false)}
        onOk={() => form.submit()}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleBatchAdjust}
        >
          <Form.Item
            label="调整方式"
            name="adjustmentType"
            rules={[{ required: true, message: '请选择调整方式' }]}
          >
            <Select placeholder="选择调整方式">
              <Option value="increase">增加库存</Option>
              <Option value="decrease">减少库存</Option>
              <Option value="set">设置库存</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            label="调整数量"
            name="quantity"
            rules={[{ required: true, message: '请输入调整数量' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={0}
              placeholder="请输入数量"
            />
          </Form.Item>
          
          <Form.Item
            label="调整原因"
            name="reason"
            rules={[{ required: true, message: '请输入调整原因' }]}
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入调整原因"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StockManagement;
